//
//  GADMasterViewController.m
//  TabBarLayoutExample
//
//  Copyright 2010 Google Inc. All rights reserved.
//

#import "GADMasterViewController.h"


@implementation GADMasterViewController

@synthesize adViewController;
@synthesize isAdLoaded;
@synthesize didCloseWebsiteView;

- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];

  id<GADMasterViewControllerDelegate> delegate =
      (id<GADMasterViewControllerDelegate>)[[UIApplication sharedApplication]
                                            delegate];
  self.adViewController = [delegate getAdViewController];
  [self.adViewController setDelegate:self];

  if(self.isAdLoaded || self.didCloseWebsiteView) {
    // Since a view can only ever have one superview, UIKit takes care of
    //  removing the ad view from its parent view when we switch tabs.  Hence,
    //  we need to re-add it when we come back.
    [self.view insertSubview:self.adViewController.view atIndex:0];
    NSLog(@"Showing previous ad");
  } else {
    self.adViewController.adSize = kGADAdSize320x50;
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
        @"Company Name", kGADAdSenseCompanyName,
        @"App Name", kGADAdSenseAppName,
        @"0", kGADAdSenseApplicationAppleID,
        @"hotels+san+francisco", kGADAdSenseKeywords,
        [NSArray arrayWithObjects:@"06562723305", nil], kGADAdSenseChannelIDs,
        [NSNumber numberWithInt:1], kGADAdSenseIsTestAdRequest,
        nil];
    [self.adViewController loadGoogleAd:attributes];
    NSLog(@"Showing new ad");
    UIView *adView = self.adViewController.view;
    CGPoint center = CGPointMake(160, 25);
    [adView setCenter:center];
    adView.center = center;

    [self.view insertSubview:adView atIndex:0];

    self.isAdLoaded = TRUE;
  }
}

- (void)viewWillDisappear:(BOOL)animated {
  self.isAdLoaded = FALSE;
  self.didCloseWebsiteView = FALSE;
  [super viewWillDisappear:animated];
}

- (UIViewController *)viewControllerForModalPresentation:
    (GADAdViewController *)adController {
  return self;
}

- (void)adControllerDidCloseWebsiteView:(GADAdViewController *)adController {
  self.didCloseWebsiteView = TRUE;
}

- (void)dealloc {
  [self.adViewController setDelegate:nil];
  self.adViewController = nil;
  [super dealloc];
}

@end
